﻿/**
 * Created by Administrator on 2018/9/30.
 */
+function ($) {
    var ExtSelect = function (f, e) {
        this.$element =  $(f);
        this.options = $.extend({}, ExtSelect.DEFAULTS, e);
        this.init()
    };
    ExtSelect.DEFAULTS = {
        width: "100%",
        language: "zh-CN",
        tags: false,
        matcher: function (l, h) {
            if ($.trim(l.term) === "") {
                return h
            }
            if (typeof h.text === "undefined") {
                return null
            }
            if ($.trim(h.text) === "") {
                return h
            }
            var g = l.term;
            var k = h.text;
            var f = Pinyin.getCamelChars(k) + "";
            var j = f.toUpperCase().indexOf(g.toUpperCase()) == 0;
            var i = k.toUpperCase().indexOf(g.toUpperCase()) == 0;
            if (j || i) {
                return h
            }
            return null
        }
    }
    ExtSelect.prototype.init = function () {
        var $select2 =  this.$element,options = this.options;
        if ($select2.find(' > option[value=""]').size() == 0) {
            var $empty = $('<option value=""></option>');
            $select2.prepend($empty)
        }
        if ($select2.find(" > option[selected]").size() == 0) {
            $select2.find("> option[value='']").attr("selected",true)
        }
        var placeholder = $select2.attr("placeholder");
        if (placeholder == undefined) {
            placeholder = "请选择..."
        }
        var allowClear = true;
        if ($select2.attr("multiple")) {
            allowClear = false
        }
        options = $.extend({
            placeholder : placeholder,
            separator: ",",
            allowClear:allowClear
        },options);
        $select2.select2(options)
    }

    function Plugin(e) {
        Bolt.assert($.fn.select2, "依赖组件 iCheck 未引入");
        return this.each(function () {
            var h = $(this);
            var g = h.data("extSelect");
            var f = typeof e == "object" && e;
            if (!g) {
                h.data("extSelect", (g = new ExtSelect(this, f)))
            }
            if (typeof e == "string") {
                g[e]()
            }
        })
    }
    $.fn.extSelect = Plugin
    $.fn.extSelect.Constructor = ExtSelect;
    $.fn.select2.defaults.set("theme", "bootstrap");

    Bolt.addComponent({
        name: "ExtSelect",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "select[data-toggle='select2']",
        order: 800
    })
}(jQuery);